package com.booklove.service.user;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.booklove.constant.MessageConstant;
import com.booklove.domain.dto.PageDTO;
import com.booklove.domain.dto.UserLoginDTO;
import com.booklove.domain.po.User;
import com.booklove.domain.query.UserQuery;
import com.booklove.exception.LoginFailedException;
import com.booklove.mapper.UserMapper;
import com.booklove.properties.WeChatProperties;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.booklove.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-09-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    final String grant_type = "authorization_code";

    final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session"; // 微信的openid的获取网址


    @Override
    public PageDTO<User> queryUsersPage(UserQuery userQuery) {
        String name = userQuery.getName();
        // 1.添加排序规则
        // 设置规则
        List<OrderItem> orderItems = userQuery.toMpOrderItems();

        // 获取分页对象和排序情况
        Page<User> page = userQuery.toMpPageDefaultSortByIdAsc(orderItems.toArray(new OrderItem[0]));
        /*
        使用lambda的方式查询
         */
        Page<User> p = lambdaQuery()
                .like(name != null, User::getUsername, name)
//                .eq(status != null, User::getStatus, status)
//                .gt(minBalance != null, User::getBalance, minBalance)
//                .lt(maxBalance != null, User::getBalance, maxBalance)
                .page(page);

        // 获取数据信息

        return PageDTO.of(p, User.class);
    }

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 解压获取的json字符串，获取字段是 openid
        String openid = getOpenid(userLoginDTO.getCode());

        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 不为空，检测是否为新用户
        User user = lambdaQuery().eq(User::getOpenid, openid).one();
        // 用户不存在的情况加入新用户
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .build();
            user.setUsername("新用户");
            user.setCreatedTime(LocalDateTime.now());
            baseMapper.insert(user);
        }

        return user;
    }

    private String getOpenid(String js_code) {
        HashMap hashMap = new HashMap();
        // 设置请求的参数，这里设置的是get请求的参数（带着？的部分的参数）
        hashMap.put("appid", weChatProperties.getAppid());
        hashMap.put("secret", weChatProperties.getSecret());
        hashMap.put("js_code", js_code);
        hashMap.put("grant_type", grant_type);
        // 使用自封工具类获取openid
        String res_json = HttpClientUtil.doGet(WX_LOGIN, hashMap);
        // 解压获取的json字符串，获取字段是 openid
        JSONObject jsonObject = JSONObject.parseObject(res_json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
